package com.mm.fam.web.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mm.fam.auth.security.TokenManager;
import com.mm.fam.common.utils.LoggerUtils;
import com.mm.fam.web.base.*;
import com.mm.fam.web.entity.SysMenu;
import com.mm.fam.web.entity.ins.AuthMenuTreeIns;
import com.mm.fam.web.service.SysMenuService;
import com.mm.fam.web.vo.UserRole;
import com.mm.fam.web.vo.UserToken;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 菜单操作
 *
 */
@Api(value="菜单模块", description="菜单模块")
@RestController
@RequestMapping(value = "/api/menu")
public class SysMenuController {

	@Autowired
	private SysMenuService sysMenuService;

	@GetMapping(value = "/queryMenuList")
	@ApiOperation(value="分页查询菜单列表", notes="分页查询菜单列表")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType="query", required=false, name = "pageNo", value = "页码", dataType = "int"),
			@ApiImplicitParam(paramType="query", required=false, name = "pageSize", value = "页数", dataType = "int"),
			@ApiImplicitParam(paramType="query", required=false, name = "search", value = "搜索条件", dataType = "string")
	})
	public ResponseEntity<ResponseModel<IPage<SysMenu>>> queryMenuList(
			@RequestParam(required = false, name = "pageNo") Integer pageNo,
			@RequestParam(required = false, name = "pageSize") Integer pageSize,
			@RequestParam(required = false, name = "search") String search){
		ResponseEntity<ResponseModel<IPage<SysMenu>>> re = null;
		try{
			re = sysMenuService.queryMenuList(pageNo, pageSize, search);
		}catch(Exception e){
			LoggerUtils.error(getClass(), "[SysMenuController queryMenuList]" + e.getMessage());
			re = ResponseUtil.error(CommonConstant.Message.OPTION_FAILURE);
		}
		return re;
	}

	@GetMapping(value = "/queryParentMenuListNoPage")
	@ApiOperation(value="不分页查询所有父级菜单", notes="不分页查询所有父级菜单")
	public ResponseEntity<ResponseModel<List<SysMenu>>> queryParentMenuListNoPage(){
		ResponseEntity<ResponseModel<List<SysMenu>>> re = null;
		try{
			re = sysMenuService.queryParentMenuListNoPage();
		}catch(Exception e){
			LoggerUtils.error(getClass(), "[SysMenuController queryParentMenuListNoPage]" + e.getMessage());
			re = ResponseUtil.error(CommonConstant.Message.OPTION_FAILURE);
		}
		return re;
	}

	@GetMapping(value = "/queryChildrenMenuListNoPage")
	@ApiOperation(value="不分页查询所有子集菜单", notes="不分页查询所有子集菜单")
	public ResponseEntity<ResponseModel<List<SysMenu>>> queryChildrenMenuListNoPage(){
		ResponseEntity<ResponseModel<List<SysMenu>>> re = null;
		try{
			re = sysMenuService.queryChildrenMenuListNoPage();
		}catch(Exception e){
			LoggerUtils.error(getClass(), "[SysMenuController queryChildrenMenuListNoPage]" + e.getMessage());
			re = ResponseUtil.error(CommonConstant.Message.OPTION_FAILURE);
		}
		return re;
	}



	@PostMapping(value = "/queryMenuTree")
	@ApiOperation(value="查询菜单并格式化为树形结构", notes="查询菜单并格式化为树形结构")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType="query", required=false, name = "search", value = "菜单名", dataType = "string")
	})
	public ResponseEntity<ResponseModel<List<SysMenu>>> queryMenuTree(String search){
		ResponseEntity<ResponseModel<List<SysMenu>>> re = null;
		try{
			re = sysMenuService.queryMenuTree(search);
		}catch(Exception e){
			LoggerUtils.error(getClass(), e.getMessage());
			re = ResponseUtil.error(CommonConstant.Message.OPTION_FAILURE);
		}
		return re;
	}

	@PostMapping(value = "/queryRoleOwnMenu")
	@ApiOperation(value="根据角色id查询该角色拥有的菜单", notes="根据角色id查询该角色拥有的菜单")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType="query", required=true, name = "roleId", value = "菜单名", dataType = "int")
	})
	public ResponseEntity<ResponseModel<List<String>>> queryRoleOwnMenu(@RequestParam(required = true, name = "roleId") Integer roleId){
		ResponseEntity<ResponseModel<List<String>>> re = null;
		try{
			re = sysMenuService.queryRoleOwnMenu(roleId);
		}catch(Exception e){
			LoggerUtils.error(getClass(), e.getMessage());
			re = ResponseUtil.error(CommonConstant.Message.OPTION_FAILURE);
		}
		return re;
	}

	@PostMapping(value = "/updateRoleOwnMenu")
	@ApiOperation(value="根据角色id查询该角色拥有的菜单", notes="根据角色id查询该角色拥有的菜单")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType="query", required=true, name = "roleId", value = "角色id", dataType = "int"),
			@ApiImplicitParam(paramType="query", required=true, name = "menuIds", value = "菜单id数组", dataType = "string")
	})
	public ResponseEntity<ResponseModel<Object>> updateRoleOwnMenu(
			@RequestParam(required = true, name = "roleId") Integer roleId,
			@RequestParam(required = true, name = "menuIds") String menuIds){
		ResponseEntity<ResponseModel<Object>> re = null;
		try{
			re = sysMenuService.updateRoleOwnMenu(roleId, menuIds);
		}catch(Exception e){
			LoggerUtils.error(getClass(), e.getMessage());
			re = ResponseUtil.error(CommonConstant.Message.OPTION_FAILURE);
		}
		return re;
	}

	@GetMapping(value = "/dynamicMenu")
	@ApiOperation(value="动态获取操作菜单接口", notes="动态获取操作菜单接口")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType="query", required=true, name = "roleId", value = "角色数组", dataType = "int")
	})
	public ResponseEntity<ResponseModel<Object>> dynamicMenu(Integer roleId){
		ResponseEntity<ResponseModel<Object>> re = null;
		try{
			re = sysMenuService.queryDynamicMenu(roleId);
		}catch(Exception e){
			LoggerUtils.error(getClass(), e.getMessage());
			re = ResponseUtil.error(CommonConstant.Message.OPTION_FAILURE);
		}
		return re;
	}

	@PostMapping(value = "/saveMenu")
	@ApiOperation(value="保存或修改菜单信息", notes="保存或修改菜单信息")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType="body", required=true, name = "sysMenu", value = "菜单对象", dataType = "SysMenu")
	})
	public ResponseEntity<ResponseModel<Object>> saveMenu(@RequestBody SysMenu sysMenu){
		ResponseEntity<ResponseModel<Object>> re = null;
		try{
			re = sysMenuService.saveMenu(sysMenu);
		}catch(Exception e){
			LoggerUtils.error(getClass(), "[SysMenuController saveMenu]" + e.getMessage());
			re = ResponseUtil.error(CommonConstant.Message.OPTION_FAILURE);
		}
		return re;
	}

	/**
	 * 获取所有菜单tree
	 * @return
	 */
	@Deprecated
	@GetMapping(value = "/getMenuTree")
	public ResponsePage<AuthMenuTreeIns> getMenuTree(@RequestParam(value="name")String name, @RequestParam(value = "current", defaultValue = "1") int current,
													 @RequestParam(value = "pageSize", defaultValue = "3") int pageSize,
													 @RequestParam(value = "search", defaultValue = "") String search) {
		//ResponseList<AuthMenuTreeIns> res = new ResponseList<AuthMenuTreeIns>();
		ResponsePage<AuthMenuTreeIns> res = new ResponsePage<AuthMenuTreeIns>();
		List<AuthMenuTreeIns> menus = null;
		try {
			SysMenu sysMenu =new SysMenu();
			sysMenu.setParentId(0);
			sysMenu.setName(name);
			sysMenu.setCurrent(current);
			sysMenu.setPageSize(pageSize);
			IPage<AuthMenuTreeIns> page = sysMenuService.getMenuTree(sysMenu);
			menus=page.getRecords();
			setMenuTree(menus, null);
			res.setPage(page);
			res.setData(menus);
		} catch (Exception e) {
			LoggerUtils.error(getClass(), "获取菜单树 失败:" + e.getMessage());
			res.failure(e.getMessage());
		}
		return res;
	}

	// 删除
	@Deprecated
	@GetMapping(value = "/delete")
	public ResponseEntitySelf<String> delete(String id) {
		ResponseEntitySelf<String> res = new ResponseEntitySelf<String>();
		try {
			boolean flag = sysMenuService.deleteMemuById(id);
			res.success("删除成功");
		} catch (Exception e) {
			LoggerUtils.error(getClass(), "菜单删除失败:" + e.getMessage());
			res.failure(CommonConstant.Message.OPTION_FAILURE);
		}
		return res;

	}

	/**
	 * 通过用户id获取菜单tree
	 *
	 * @return
	 */
	@Deprecated
	@GetMapping(value = "/getUserMenuTree")
	public ResponseList<AuthMenuTreeIns> userTree() {
		ResponseList<AuthMenuTreeIns> res = new ResponseList<AuthMenuTreeIns>();
		List<AuthMenuTreeIns> menus = null;
		try {
			UserToken token = TokenManager.getToken();
			menus = sysMenuService.getMenuTreeByUserId(token.getId());
			res.setData(menus);
		} catch (Exception e) {
			LoggerUtils.error(getClass(), "通过用户id 获取用户菜单树 失败:" + e.getMessage());
			res.failure(e.getMessage());
		}
		return res;
	}



	/**
	 * 批量删除
	 *
	 * @return
	 */
	@Deprecated
	@PostMapping(value = "/deleteBatch")
	public ResponseEntitySelf<String> deleteBatch(@RequestBody Map<String, Object> param) {
		ResponseEntitySelf<String> res = new ResponseEntitySelf<String>();
		List<String> ids = (List<String>) param.get("ids");
		try {
			sysMenuService.deleteBatch(ids);
			res.success(CommonConstant.Message.OPTION_SUCCESS);
		} catch (Exception e) {
			LoggerUtils.error(getClass(), "批量删除菜单失败:" + e.getMessage());
			res.failure(CommonConstant.Message.OPTION_FAILURE);
		}
		return res;
	}

	/**
	 * 设置权限树 状态(设置 是否选中)
	 *
	 * @param trees
	 *            菜单树
	 * @param mapHasMenusMenus
	 *            具有权限的菜单
	 */
	private boolean setMenuTree(List<AuthMenuTreeIns> trees, Map<Integer, SysMenu> mapHasMenusMenus) {
		if (trees == null || trees.isEmpty())
			return false;
		boolean flag = false;
		for (AuthMenuTreeIns tree : trees) {
			if (mapHasMenusMenus != null && mapHasMenusMenus.containsKey(tree.getId())) {
				tree.setChecked(true);
				flag = true;
			}
			if (tree.getChildren() != null && !tree.getChildren().isEmpty()) {
				tree.setIsParent(true);
				if (setMenuTree(tree.getChildren(), mapHasMenusMenus)) {
					tree.setChecked(true);
				}
			}
		}
		return flag;
	}

	/**
	 * 处理角色id
	 * @param roles
	 * @return
	 */
	private List<Integer> getRolesId(List<UserRole> roles) {
		List<Integer> tempRoles = new ArrayList<Integer>();
		for(UserRole u : roles) {
			tempRoles.add(u.getId());
		}
		return tempRoles;
	}

}
